/**

 @Name：layuiAdmin 用户管理 管理员管理 角色管理
 @Author：star1029
 @Site：http://www.layui.com/admin/
 @License：LPPL
    
 */


layui.define(['table', 'form', 'transfer', 'tree'], function (exports) {
    var $ = layui.$
      , admin = layui.admin
      , view = layui.view
      , table = layui.table
      , form = layui.form
      , tree = layui.tree;
    var transfer = layui.transfer;
    //用户管理
    table.render({
      elem: '#LAY-user-manage'
      , url: 'http://stuapi.ysdjypt.com/api/GetUsersLayUI' //模拟接口
      , method: 'post'
      , where: {
        token: '69f84759-5242-488f-b98c-88b8e504dd95'
      }
      , cols: [[
        { type: 'checkbox', fixed: 'left' }
        , { field: 'Id', width: 100, title: 'ID', sort: true }
        , { field: 'RowNum', title: '行号' }
        , { field: 'LoginName', title: '用户名', minWidth: 100 }
        , {
          field: '', title: '是否锁定', width: 80, templet: function (d) {
            if (d.IsLockout == "是") {
              //console.log(d.LoginName);
              return '<input type="checkbox" param="' + d.LoginName + '" lay-filter="Lockout" name="IsLockout" lay-skin="switch" checked="checked"   lay-text="是|否">'
            } else {
              return '<input type="checkbox" param="' + d.LoginName + '" lay-filter="unLocakout" name="IsLockout" lay-skin="switch"   lay-text="是|否">';
            }
          }
        }/* templet: '#imgTpl' */
        /* ,templet:function(d){
          if(d.IsLockout=="否"){
            return '<input type="checkbox" param="'+d.id+'" lay-filter="Lockout" name="IsLockout" lay-skin="switch" checked  lay-text="是|否">'
          }else{
                return '<input type="checkbox" param="'+d.id+'" lay-filter="unLocakout" name="IsLockout" lay-skin="switch"   lay-text="是|否">';
            }
        } */
        , { field: 'LastLoginTime', title: '最后登录时间', sort: true, width: 160 }
        , { field: 'CreateTime', title: '创建时间', width: 160, sort: true }
        , { field: 'PsdWrongTime', width: 80, title: '密匙错误次数' }
        , { field: 'LockTime', title: '用户锁定时间' }
        , { field: 'ProtectEMail', title: '邮箱' }
        , { field: 'ProtectMTel', title: '手机号码' }
        , { title: '操作', width: 280, align: 'center', fixed: 'right', toolbar: '#table-useradmin-webuser' }
      ]]
      , page: true
      , limit: 10
      , limits: [10, 20, 30]
      , height: 'full-320'
      , text: '对不起，加载出现异常！'
    });
    form.on('switch(Lockout)', function (data) {
      console.log(data.elem); //得到checkbox原始DOM对象
      console.log(data.elem.checked); //开关是否开启，true或者false
      console.log(data.value); //开关value值，也可以通过data.elem.value得到
      console.log(data.othis); //得到美化后的DOM对象
      //console.log($(data.elem).attr("param"));
      if(data.elem.checked){
        $.post(
          "http://stuapi.ysdjypt.com/api/LockUser"
          , {
            un: $(data.elem).attr("param")
            , token: '69f84759-5242-488f-b98c-88b8e504dd95'
          }, function (res) {
            if (res) {
              layer.msg("操作成功");
            } else {
              layer("操作失败");
            }
          }, 'json'
        )
      }else{
        $.post(
          "http://stuapi.ysdjypt.com/api/unLockUser"
          , {
            un: $(data.elem).attr("param")
            , token: '69f84759-5242-488f-b98c-88b8e504dd95'
          }, function (res) {
            if (res) {
              layer.msg("操作成功");
            } else {
              layer("操作失败");
            }
          }, 'json'
        )
  
      }
      //console.log(data.elem.checked);
    });
    form.on('switch(unLocakout)', function (data) {
      console.log(data.elem); //得到checkbox原始DOM对象
      console.log(data.elem.checked); //开关是否开启，true或者false
      console.log(data.value); //开关value值，也可以通过data.elem.value得到
      console.log(data.othis); //得到美化后的DOM对象
      console.log($(data.elem).attr("param"));
      $.post(
        "http://stuapi.ysdjypt.com/api/LockUser"
        , {
          un: $(data.elem).attr("param")
          , token: '69f84759-5242-488f-b98c-88b8e504dd95'
        }, function (res) {
          if (res) {
            layer.msg("操作成功");
          } else {
            layer("操作失败");
          }
        }, 'json'
      )
      //console.log(data.elem.checked);
    });
    //监听工具条
    table.on('tool(LAY-user-manage)', function (obj) {
      var data = obj.data;
      var transferId = data.Id;
      //console.log(transferId);
      if (obj.event === 'del') {
        layer.prompt({
          formType: 1
          , title: '敏感操作，请验证口令'
        }, function (value, index) {
          layer.close(index);
          console.log(data.Id);
          layer.confirm('真的删除行么', function (index) {
            $.post(
              "http://stuapi.ysdjypt.com/api/DeleteUser"
              , {
                uid: data.Id
                , token: '69f84759-5242-488f-b98c-88b8e504dd95'
              }
              , function (res) {
                if (res) {
                  layer.msg("删除成功");
                } else {
                  layer.msg("删除失败")
                }
              }
            )
            obj.del();
            layer.close(index);
          });
        });
      } else if (obj.event === 'edit') {
        admin.popup({
          title: '编辑用户'
          , area: ['500px', '450px']
          , id: 'LAY-popup-user-add'
          , success: function (layero, index) {
            view(this.id).render('user/user/usereditform', data).done(function () {
              form.render(null, 'layuiadmin-form-useradmin');
              form.val("layuiadmin-form-useradmin", data);
              //监听提交
              form.on('submit(LAY-user-front-usereditsubmit)', function (data) {
                var field = data.field; //获取提交的字段
                /* var loginName=$("#loginName").val();
                var email=$("#ProtectEMail").val();
                var mtel=$("#mtel").val();
                var token=$("#token").val();
                var pwd=$("#pwd").val(); */
                console.log(form.val("layuiadmin-form-useradmin", data));
                console.log(loginName);
                $.ajax({
                  url: "http://stuapi.ysdjypt.com/api/UpdateUser"
                  , type: 'post'
                  , data: field
                  , success: function (data) {
                    layer.msg("修改成功");
                    layui.table.reload('LAY-user-manage'); //重载表格
                    layer.close(index); //执行关闭 
                  }, error: function (data) {
                    layer.msg("修改失败");
                  }
                })
                /* $.post(
                  "http://stuapi.ysdjypt.com/api/UpdateUser"
                  ,{
                    "loginName":loginName
                    ,"email":email
                    ,"pwd":pwd
                    ,"mtel":mtel
                    ,"token":token
                  }
                  ,function(res) {
                    if(res){
                      layer.msg("修改成功");
                      //layui.table.reload('LAY-user-manage'); //重载表格
                      //layer.close(index); //执行关闭 
                    }else{
                      layer.msg("修改失败");
                    }
                  },'json'
                ); */
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                //$.ajax({});
  
              });
            });
          }
        });
      } else if (obj.event === 'userroles') {
        admin.popup({
          title: '给角色'
          , area: ['600px', '500px']
          , id: 'LAY-popup-user-add'
          , success: function (layero, index) {
            view(this.id).render('user/user/userroles', data).done(function () {
              //form.render(null, 'layuiadmin-form-userroles');
              //console.log(data.Id);
              $.post(
                "http://stuapi.ysdjypt.com/api/GetRolesByUserIdLayUI"
                , {
                  uid: data.Id
                  , token: '69f84759-5242-488f-b98c-88b8e504dd95'
                }, function (res) {
                  //console.log(res);
                  var valueArr = new Array();
                  for (var i = 0; i < res.data.length; i++) {
                    //console.log(res.data[i].Id);
                    valueArr.push(res.data[i].Id);
                  }
                  $.post(
                    "http://stuapi.ysdjypt.com/api/GetRolesAll"
                    , {
                      token: '69f84759-5242-488f-b98c-88b8e504dd95'
                    }
                    , function (res) {
                      //console.log(data.LoginName);
                      //渲染
                      transfer.render({
                        elem: '#uesrroles'  //绑定元素
                        , title: ["所有角色", "用户角色"]
                        , data: res
                        , parseData: function (res) {
                          return {
                            "value": res.Id //数据值
                            , "title": res.Name //数据标题
                            , "disabled": res.disabled  //是否禁用
                            , "checked": res.checked //是否选中
                          }
                        }
                        , value: valueArr
                        , id: 'demo1' //定义索引
                        , onchange: function (data, index) {
                          console.log(data); //得到当前被穿梭的数据
                          console.log(index); //如果数据来自左边，index 为 0，否则为 1
                          //console.log(data.value);
                          if (index == 0) {
                            for (var i = 0; i < data.length; i++) {
  
                              $.post(
                                "http://stuapi.ysdjypt.com/api/AddUserToRole"
                                , {
                                  uId: transferId
                                  , rId: data[i].value
                                  , token: '69f84759-5242-488f-b98c-88b8e504dd95'
                                }
                                , function (res) {
                                  layer.msg("分配角色成功");
  
                                }, 'json'
                              );
                            }
                          } else {
                            for (var i = 0; i < data.length; i++) {
  
                              $.post(
                                "http://stuapi.ysdjypt.com/api/RemoveUserFromRole"
                                , {
                                  uId: transferId
                                  , rId: data[i].value
                                  , token: '69f84759-5242-488f-b98c-88b8e504dd95'
                                }
                                , function (res) {
                                  layer.msg("移除角色成功");
  
                                }, 'json'
                              );
                            }
                          }
                        }
                      });
                    }, 'json'
                  );
                }, 'json'
              );
              //监听提交
              /* form.on('submit(LAY-user-front-usereditsubmit)', function(data){
                var field = data.field; //获取提交的字段
               
                console.log(form.val("layuiadmin-form-useradmin",data));
                console.log(data.id);
                console.log(loginName);
                layer.msg("true");
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                //$.ajax({});
                
              }); */
            });
          }
        });
      } else if (obj.event === 'reset') {
        var data = obj.data;
        if (obj.event === 'reset') {
          layer.prompt({
            formType: 1
            , title: '敏感操作，请验证口令'
          }, function (value, index) {
            layer.close(index);
            console.log(data.LoginName);
            layer.confirm('真的重置当前密码么', function (index) {
              $.ajax({
                url: "http://stuapi.ysdjypt.com/api/ResetPassword"
                , type: "post"
                , data: {
                  un: data.LoginName
                  , token: '69f84759-5242-488f-b98c-88b8e504dd95'
                },
                success: function (res) {
                  layer.msg("重置密码成功");
                }, error: function (res) {
                  layer.msg("重置密码失败");
                }
              });
              /* $.post(
                "http://stuapi.ysdjypt.com/api/ResetPassword"
                ,{
                  un:data.LoginName
                  ,token:'69f84759-5242-488f-b98c-88b8e504dd95'
                }
                ,function(res){
                  if(res>0){
                    layer.msg("重置密码成功");
                  }else{
                    layer.msg("重置密码失败")
                  }
                }
              ) */
              layer.close(index);
            });
          });
        }
      }
    });
  
    //管理员管理
    table.render({
      elem: '#LAY-user-back-manage'
      , url: './json/useradmin/mangadmin.js' //模拟接口
      , cols: [[
        { type: 'checkbox', fixed: 'left' }
        , { field: 'id', width: 80, title: 'ID', sort: true }
        , { field: 'loginname', title: '登录名' }
        , { field: 'telphone', title: '手机' }
        , { field: 'email', title: '邮箱' }
        , { field: 'role', title: '角色' }
        , { field: 'jointime', title: '加入时间', sort: true }
        , { field: 'check', title: '审核状态', templet: '#buttonTpl', minWidth: 80, align: 'center' }
        , { title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-useradmin-admin' }
      ]]
      , text: '对不起，加载出现异常！'
    });
  
    //监听工具条
    table.on('tool(LAY-user-back-manage)', function (obj) {
      var data = obj.data;
      if (obj.event === 'del') {
        layer.prompt({
          formType: 1
          , title: '敏感操作，请验证口令'
        }, function (value, index) {
          layer.close(index);
          layer.confirm('确定删除此管理员？', function (index) {
            console.log(obj)
            obj.del();
            layer.close(index);
          });
        });
      } else if (obj.event === 'edit') {
        admin.popup({
          title: '编辑管理员'
          , area: ['420px', '450px']
          , id: 'LAY-popup-user-add'
          , success: function (layero, index) {
            view(this.id).render('user/administrators/adminform', data).done(function () {
              form.render(null, 'layuiadmin-form-admin');
  
              //监听提交
              form.on('submit(LAY-user-back-submit)', function (data) {
                var field = data.field; //获取提交的字段
  
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                //$.ajax({});
                layui.table.reload('LAY-user-back-manage'); //重载表格
                layer.close(index); //执行关闭 
              });
            });
          }
        });
      }
    });
  
    //角色管理
    table.render({
      elem: '#LAY-user-back-role'
      , url: 'http://stuapi.ysdjypt.com/api/GetRolesLayUI' //模拟接口
      , method: 'post'
      , where: {
        token: '69f84759-5242-488f-b98c-88b8e504dd95'
      }
      /* ,parseData:function(res){
        console.log(res)
        return {
          "code":0
          ,"msg":""
          ,"count":res.id
          ,"data":res
        };
      }  */
      , cols: [[
        { type: 'checkbox', fixed: 'left' }
        , { field: 'RowNum', width: 80, title: '行号', sort: true }
        , { field: 'Id', width: 300, title: '角色id ', sort: true }
        , { field: 'Name', title: '角色名称' }
        , { title: '操作', width: 200, align: 'center', fixed: 'right', toolbar: '#table-useradmin-admin' }
      ]]
      , page: true
      , limit: 10
      , limits: [10, 20, 30]
      , text: '对不起，加载出现异常！'
    });
  
    //监听工具条
    table.on('tool(LAY-user-back-role)', function (obj) {
      var data = obj.data;
      if (obj.event === 'del') {
        layer.confirm('确定删除此角色？', function (index) {
          $.ajax({
            url: "http://stuapi.ysdjypt.com/api/DeleteRole "
            , type: 'post'
            , data: {
              roleId: data.Id
              , token: '69f84759-5242-488f-b98c-88b8e504dd95'
            }, success: function (res) {
              layer.msg("删除成功");
              obj.del();
              layer.close(index);
            }, error: function (res) {
              layer.msg("删除失败");
            }
          });
          //obj.del();
  
        });
      } else if (obj.event === 'edit') {
        admin.popup({
          title: '编辑角色'
          , area: ['500px', '480px']
          , id: 'LAY-popup-user-add'
          , success: function (layero, index) {
            view(this.id).render('user/administrators/roleform', data).done(function () {
              form.render(null, 'layuiadmin-form-role');
              form.val("layuiadmin-form-role", data);
              console.log(data.Id);
              console.log(data.Name);
  
              //监听提交
              form.on('submit(LAY-user-role-submit)', function (data) {
                var field = data.field; //获取提交的字段
                console.log(field.name);
                console.log(field.Id);
                $.ajax({
                  url: "http://stuapi.ysdjypt.com/api/UpdateRole"
                  , type: 'post'
                  , data: {
                    name: $("#name").val()
                    , roleId: $("#Id").val()
                    , token: '69f84759-5242-488f-b98c-88b8e504dd95'
                  }
                  , success: function (data) {
                    layer.msg("角色修改成功");
                    layui.table.reload('LAY-user-back-role'); //重载表格
                    layer.close(index); //执行关闭 
                  }, error: function (data) {
                    layer.msg("角色修改失败");
                  }
                });
                /* $.post(
                  "http://stuapi.ysdjypt.com/api/UpdateRole"
                  ,field
                  ,function(data){
                    if(data.success){
                      layer.msg("true");
                    }else{
                      layer.msg("false");
                    }
                  },'json'
                ); */
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                //$.ajax({});
                //layui.table.reload('LAY-user-back-role'); //重载表格
                //layer.close(index); //执行关闭 
              });
            });
          }
        });
      } else if (obj.event === 'power') {
        admin.popup({
          title: '角色权限'
          , area: ['550px', '500px']
          , id: 'LAY-popup-user-power'
          , success: function (layero, index) {
            view(this.id).render('user/administrators/power', data).done(function () {
              //form.render(null, 'layuiadmin-form-role');
              //console.log(data.Id);
              //console.log(data.Name);
  
              $.post(
                "http://stuapi.ysdjypt.com/api/GetModulesByRoleIdLayUI"
                , {
                    roleId: data.Id
                    , token: '69f84759-5242-488f-b98c-88b8e504dd95'
                }
                , function (res) {
                    //渲染
                    var inst1 = tree.render({
                        elem: '#power'  //绑定元素
                        , id: 'demoId' //定义索引
                        , showCheckbox: true
                        , edit: ['add', 'update', 'del']
                        , data: res
                        , click: function (obj) {
                            console.log(obj.data); //得到当前点击的节点数据
                            console.log(obj.state); //得到当前节点的展开状态：open、close、normal
                            console.log(obj.elem); //得到当前节点元素
  
                            //console.log(obj.data.children); //当前节点下是否有子节点
                        }
                        , oncheck: function (obj) {
                            console.log(obj.data); //得到当前点击的节点数据
                            console.log(obj.checked); //得到当前节点的展开状态：open、close、normal
                            console.log(obj.elem); //得到当前节点元素
                        }
                        , operate: function (obj) {
                            var type = obj.type; //得到操作类型：add、edit、del
                            var data = obj.data; //得到当前节点的数据
                            var elem = obj.elem; //得到当前节点元素
                            var parentId=data.id;
                            //console.log(parentId);
                            //Ajax 操作
                            var id = data.id; //得到节点索引
                            if (type === 'add') { //增加节点
                            console.log(data);
                                $.post(
                                    "http://stuapi.ysdjypt.com/api/CreateModule"
                                    , {
                                        name: data.title
                                        , parentId: data.id
                                        , path: data.href
                                        , weight: '1'
                                        , token: '69f84759-5242-488f-b98c-88b8e504dd95'
                                    }
                                    , function (res) {
                                        /* if (res.success) {
                                            layer.msg("添加节点成功");
                                        }else{
                                            layer.msg("添加节点失败");
                                        } */
                                            layer.msg(res.success);
                                        //console.log(res);
                                    },'json'
                                );
                                //返回 key 值
                                return 123;
                            } else if (type === 'update') { //修改节点
                            console.log(data.id);
                                $.post(
                                    "http://stuapi.ysdjypt.com/api/UpdateModule"
                                    , {
                                        mId:data.id
                                        ,name: data.title
                                        , parentId: parentId
                                        , path: data.href
                                        , weight: '2'
                                        , token: '69f84759-5242-488f-b98c-88b8e504dd95'
                                    }
                                    , function (res) {
                                        if (res.success) {
                                            layer.msg("修改节点成功");
                                        }else{
                                            layer.msg("修改节点失败");
                                        }
                                        //console.log(res);
                                    },'json'
                                );
                                //layer.msg("编辑节点");
                                console.log(elem.find('.layui-tree-txt').html()); //得到修改后的内容
                            } else if (type === 'del') { //删除节点
                                layer.msg("删除节点");
                                $.post(
                                    "http://stuapi.ysdjypt.com/api/DeleteModule"
                                    , {
                                        mId:data.id
                                        , token: '69f84759-5242-488f-b98c-88b8e504dd95'
                                    }
                                    , function (res) {
                                        if (res) {
                                            layer.msg("删除节点成功");
                                        }else{
                                            layer.msg("删除节点失败");
                                        }
                                        //console.log(res);
                                    },'json'
                                );
                            };
                        }
                    });
                }, 'json'
            );
  
            $("#btn").on('click', function () {
                //获得选中的节点
                var checkData = tree.getChecked('demoId');
                for(var i=0;i<=checkData.length;i++){
                    console.log(checkData[i]);
                }
                $.post(
                    "http://stuapi.ysdjypt.com/api/SetSysRights"
                    ,{
                        parentIds:checkData
                        ,rId:'37da0768-4100-4ff3-b9d7-0cc58aae2a7c'
                        ,token: '69f84759-5242-488f-b98c-88b8e504dd95'
                    }
                    ,function(res){
                        layer.msg(res.success);
                    },'json'
                );
                console.log(checkData);
            });
            });
          }
        });
      }
    });
  
    exports('useradmin', {})
  });